package cn.maxhou.sz4;

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

@Configuration
@PropertySource(value = "classpath:database.properties",encoding = "UTF-8")
@ImportResource("classpath:applicationContext-mybatis.xml")
public class JavaConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Value("${pool.maxTotal}")
    private int maxTotal;
    @Value("${pool.initialSize}")
    private int initialSize;
    @Value("${pool.minIdle}")
    private int minIdle;
    @Value("${pool.maxIdle}")
    private int maxIdle;
    @Value("${pool.maxWaitMillis}")
    private int maxWaitMillis;

    @Value("${pool.removeAbandonedOnBorrow}")
    private boolean removeAbandonedOnBorrow;
    @Value("${pool.removeAbandonedOnMaintenance}")
    private boolean removeAbandonedOnMaintenance;
    @Value("${pool.removeAbandonedTimeout}")
    private int removeAbandonedTimeout;
    //定义dbcp2数据源
    @Bean
    public BasicDataSource basicDataSource(){
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUrl(url);
        basicDataSource.setUsername(username);
        basicDataSource.setPassword(password);
        basicDataSource.setMaxTotal(maxTotal);
        basicDataSource.setInitialSize(initialSize);
        basicDataSource.setMinIdle(minIdle);
        basicDataSource.setMaxIdle(maxIdle);
        basicDataSource.setMaxWaitMillis(maxWaitMillis);
        basicDataSource.setRemoveAbandonedOnBorrow(removeAbandonedOnBorrow);
        basicDataSource.setRemoveAbandonedOnMaintenance(removeAbandonedOnMaintenance);
        basicDataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        return basicDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(basicDataSource());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean;
    }
}
